package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;

import vrp.PMF;
import vrp.Product;
import vrp.SaleOrder;

public class ProductDeleteServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
    	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
        long keyid = Integer.parseInt(req.getParameter("key"));
        
        Key key = KeyFactory.createKey(Product.class.getSimpleName(), keyid);
        Product product = pm.getObjectById(Product.class, key);
        
        //check whether product has been placed in any sale order
        //if yes, cannot delete
        Query query = pm.newQuery(SaleOrder.class);
        query.setFilter("product == productKeypara");
        query.declareParameters("String productKeypara");
        List<SaleOrder> saleOrders = (List<SaleOrder>) query.execute(key);
        if (saleOrders.size()!=0) {
        	pm.close();
        	resp.sendRedirect("/products.jsp?error=inuse");
        	return;
        }
        
        try {
            pm.deletePersistent(product);
        } finally {
            pm.close();
        }
        resp.sendRedirect("/products.jsp");
    }
}
